package com.scaffold.springbootscaffold.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class WebSocketSessionManager {
    
    // 存储用户ID和session ID的映射
    private static final Map<String, String> USER_SESSION_MAP = new ConcurrentHashMap<>();
    // 存储session ID和用户ID的映射
    private static final Map<String, String> SESSION_USER_MAP = new ConcurrentHashMap<>();

    public void addSession(String userId, String sessionId) {
        USER_SESSION_MAP.put(userId, sessionId);
        SESSION_USER_MAP.put(sessionId, userId);
        log.info("用户{}连接成功，当前在线人数：{}", userId, USER_SESSION_MAP.size());
    }

    public void removeSession(String sessionId) {
        String userId = SESSION_USER_MAP.remove(sessionId);
        if (userId != null) {
            USER_SESSION_MAP.remove(userId);
            log.info("用户{}断开连接，当前在线人数：{}", userId, USER_SESSION_MAP.size());
        }
    }

    public String getUserId(String sessionId) {
        return SESSION_USER_MAP.get(sessionId);
    }

    public String getSessionId(String userId) {
        return USER_SESSION_MAP.get(userId);
    }

    public boolean isOnline(String userId) {
        return USER_SESSION_MAP.containsKey(userId);
    }

    public Map<String, String> getOnlineUsers() {
        return new ConcurrentHashMap<>(USER_SESSION_MAP);
    }
} 